import type { MarkdownInstance } from "astro"
import ProjectTxt from "@content/projects/_projects.txt?raw"
import { getId } from "../utils/get-id"

interface Image {
	src: string
	alt: string
}

interface BaseProjectFrontmatter {
	link: string
	title: string
	links: Array<{
		href: string
		title: string
		icon: string
	}>
	color?: string
	time?: string
	index?: number
}

export type BaseProject = MarkdownInstance<BaseProjectFrontmatter>
export type PageProject = MarkdownInstance<
	BaseProjectFrontmatter & {
		cover?: string
		images?: Image[]
	}
>

export type Project = BaseProject | PageProject

const projectsOrder = ProjectTxt.trim()
	.split("\n")
	.map((line) => line.trim())
	.filter((line) => line.length > 0)

export const sortProjects = (files: MarkdownInstance<any>[]): Project[] => {
	const result = new Array(projectsOrder.length)
	files.forEach((file) => {
		const id = getId(file)
		if (!id) return
		const index = projectsOrder.indexOf(id)
		if (index < 0) return result.push(file)
		result[index] = file
	})
	return result
}

export const isProjectLink = (href: string) => href.startsWith("/")

export const needsProjectPage = ({ frontmatter: { link, links } }: Project) => {
	if (isProjectLink(link)) return true
	return links.findIndex(({ href }) => isProjectLink(href)) !== -1
}
